<?php
/**
 * vim: tabstop=4
 * 
 * @license		http://www.gnu.org/licenses/gpl.html GPL Version 3
 * @author		Ian Moore <imooreyahoo@gmail.com>
 * @copyright	Copyright (c) 2011 Ian Moore
 * @version		$Id: minidlna.inc 73 2011-12-10 02:17:04Z imooreyahoo@gmail.com $
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
require_once("openmediavault/module.inc");
require_once("openmediavault/config.inc");
require_once("openmediavault/error.inc");
require_once("openmediavault/util.inc");
require_once("openmediavault/initscript.inc");
require_once("openmediavault/log.inc");

class MiniDLNAModule extends OMVModuleAbstract implements OMVINotifyListener,
  OMVIModuleStatus {
	/**
	 * Get the module name.
	 */
	public static function getName() {
		return "minidlna";
	}

	/**
	 * Get the module status.
	 */
	public function getStatus() {
		global $xmlConfig;
		// Get the configuration object
		$xpath = "//services/minidlna";
		$object = $xmlConfig->get($xpath);
		if (is_null($object)) {
			throw new OMVException(OMVErrorMsg::E_CONFIG_GET_OBJECT_FAILED,
			  $xpath);
		}
		$initd = new OMVSysVInitScript("minidlna");
		return array(
			"name" => $this->getName(),
			"title" => gettext("MiniDLNA"),
			"enabled" => boolval($object['enable']),
			"running" => ($initd->status() == 0)
		);
	}

	/**
	 * Create the configuration file and update the service.
	 */
	public function updateService($conf,$oldconf,$rescan) {

		// Create '/etc/minidlna.conf' file
		$cmd = "sudo omv-mkconf minidlna 2>&1";
		OMVUtil::exec($cmd, $output, $result);
		if ($result !== 0) {
			throw new OMVException(OMVErrorMsg::E_EXEC_FAILED,
			  $cmd, implode("\n", $output));
		}

		$initd = new OMVSysVInitScript("minidlna");

		// Should the service be started with force-reload?
		if($conf['enable'] && $rescan) {

            $cmd = "sudo /etc/init.d/minidlna force-reload 2>&1";
            OMVUtil::exec($cmd, $output, $result);
            if ($result !== 0) {
                throw new OMVException(OMVErrorMsg::E_EXEC_FAILED,
                    $cmd, implode("\n", $output));
            }

		} elseif($conf['enable']) {

			$new_folders = array();
			$old_folders = array();

			foreach($conf['folders'] as $f)
				$new_folders[$f['sfref']] = (string)$f['mtype'];

			foreach($oldconf['folders'] as $f)
				$old_folders[$f['sfref']] = (string)$f['mtype'];

			ksort($new_folders);
			ksort($old_folders);


			// Force -reload if folders have changed or it wasn't
			// previously enabled
			if(!$oldconf['enable'] || serialize($new_folders) != serialize($old_folders)) {
				$cmd = "sudo /etc/init.d/minidlna force-reload 2>&1";
		        OMVUtil::exec($cmd, $output, $result);
		        if ($result !== 0) {
		            throw new OMVException(OMVErrorMsg::E_EXEC_FAILED,
        		      $cmd, implode("\n", $output));
		        }

			// Normal restart
			} else {
				$initd->restart();
			}

		// Going from enabled to disabled
		} else if($oldconf['enable']) {

			$initd->stop();

		}

	}

	/**
	 * Bind listeners.
	 */
	function bindListeners(OMVNotifyDispatcher $dispatcher) {

		// Update service if configuration has been modified
		$dispatcher->addListener(
		  OMV_NOTIFY_MODIFY,
		  "org.openmediavault.services.minidlna",
		  array($this, "updateService"), 1);

	}
}

// Register module
$moduleMgr = &OMVModuleMgr::getInstance();
$moduleMgr->registerModule(new MiniDLNAModule());

// Register new logfile type
OMVLogFile::registerType("minidlna", array(
  "filename" => "minidlna.log",
  "filepath" => "/var/log/minidlna.log",
  "regex" => "/^\[(.*?)\]\s+(.*?)\..*?:\d+:\s+.*?:\s+(.*)$/",
  "columns" => array(
	  "date" => array(
		  "index" => 1,
		  "func" => create_function('$v', 'return strpdate($v,"Y/n/j G:i:s");')
	  ),
	  "component" => 2,
      "event" => 3
  )));

